#!/usr/bin/python3

import tkinter as tk
from tkinter.font import Font
import os,sys,copy
import sqlite3
from lxml import etree
import urllib.request
import urllib.parse

class Window:
    def __init__(self, title='输入字典项', width=800, height=600, staFunc=bool, stoFunc=bool):
        self.w = width
        self.h = height
        self.stat = True
        self.staFunc = staFunc
        self.stoFunc = stoFunc
        self.staIco = None
        self.stoIco = None
        self.root = tk.Tk(className=title)

    def center(self):
        ws = self.root.winfo_screenwidth()
        hs = self.root.winfo_screenheight()
        x = int( (ws/2) - (self.w/2) )
        y = int( (hs/2) - (self.h/2) )
        self.root.geometry('{}x{}+{}+{}'.format(self.w, self.h, x, y))   
        
    def packBtn(self):
        self.f1=tk.Frame(self.root)
        self.f2=tk.Frame(self.root)
        self.f3=tk.Frame(self.root)
        self.f1.pack(side='top')
        self.f2.pack(fill=tk.BOTH,expand=True,side='top')
        self.f3.pack(side='top')
        
        self.entry1 = tk.Entry(self.f1, font=Font(size=16))    
        self.entry1.pack(side='left')
        
        self.btnSelect=tk.Button(self.f1, command=self.baidudict, width=15, height=3)
        self.btnSelect.pack(padx=10, side='left')
        self.btnSelect['text'] = '百度字典'
             
        self.text1 = tk.Text(self.f2, width=0, height=0 , font=Font(size=16) )
        self.scroll1 = tk.Scrollbar( self.f2, width=20 )
        self.scroll1.pack(side='right', fill=tk.Y)
        self.text1.pack( fill=tk.BOTH,expand=True,side='left' )
        self.scroll1['command'] = self.text1.yview
        self.text1['yscrollcommand'] = self.scroll1.set
        
        self.btnSelect=tk.Button(self.f3, command=self.input_word, width=15, height=3)
        self.btnSelect.pack(padx=10, side='left')
        self.btnSelect['text'] = '输入文字'

        btnQuit = tk.Button(self.f3, text='关闭窗口', command=self.root.quit, width=15, height=3)
        btnQuit.pack(padx=10, side='right')
        
    def input_word(self):
        wd = self.entry1.get()
        mean = self.text1.get('0.0', tk.END)
#        print(wd) 
#        print( mean)
        db1 = sqlite3.connect( os.path.join(os.getcwd(), 'mydict.db') )
        db1.text_factory = str
        cu1 = db1.cursor()
        try:
            cu1.execute( "REPLACE into dict(word, mean) values( ? , ? )", (wd, mean))
            self.text1.delete('1.0', tk.END)
            self.entry1.delete(0, tk.END)
        except:
            print('insert error')
        cu1.close()
        db1.commit()
        db1.close()
            
    def baidudict(self):
        self.text1.delete('0.0', tk.END)
        
        p1 = urllib.parse.urlencode({'wd':self.entry1.get(),'ptype':'zici'})
        url1 = 'http://dict.baidu.com/s?%s' % p1
        opener = urllib.request.build_opener()
        opener.addheaders = [('User-agent', 'Mozilla/5.0')]
        fp1 = opener.open(url1)
        s = fp1.read().decode('utf-8')

        dom = etree.HTML( s )

        means = dom.xpath('//div[@id="basicmean-wrapper"]/div/dl')
        for mean1 in means:
            duyin = mean1.xpath('dt')
            for dy1 in duyin:
                if dy1.text is not None:
                    self.text1.insert(tk.END,'读音：'+dy1.text+'\n')
            self.text1.insert(tk.END,'解释：\n')
            jieshi = mean1.xpath('dd/p')
            for m in jieshi:
                if m.text is not None:
                    self.text1.insert(tk.END,m.text+'\n')
            self.text1.insert(tk.END,'\n')

    def loop(self):
        self.root.resizable(False, False)   #禁止修改窗口大小
        self.packBtn()
        self.center()                       #窗口居中
        self.root.mainloop()

########################################################################

def change_dir():
    cwd = os.path.split(sys.argv[0])
    if len(cwd[0])>0:
        os.chdir(cwd[0])
        
if __name__ == '__main__':
    change_dir()
    w = Window()
    w.loop()
